package com.gly091020;

import com.gly091020.config.ChineseChestConfig;
import com.gly091020.util.ChineseChestNetworkID;
import me.shedaniel.autoconfig.AutoConfig;
import me.shedaniel.autoconfig.serializer.GsonConfigSerializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.entity.LootableContainerBlockEntity;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;

import java.lang.reflect.Field;
import java.util.UUID;

public class ChineseChest implements ModInitializer {
    public static final String ModID = "chinese_chest";
    public static ChineseChestConfig config;
    public static final UUID _5112151111121 = UUID.fromString("91bd580f-5f17-4e30-872f-2e480dd9a220");
    private static Field lootTableIdField;
    private static Field lootTableSeedField;

    static{
        try {
            lootTableIdField = LootableContainerBlockEntity.class.getDeclaredField("lootTableId");
            lootTableSeedField = LootableContainerBlockEntity.class.getDeclaredField("lootTableSeed");
        } catch (NoSuchFieldException ignored){
            try {
                // 这个地方必须填混淆后的字段名
                // https://maven.fabricmc.net/docs/yarn-1.20+build.1/net/minecraft/block/entity/LootableContainerBlockEntity.html
                lootTableIdField = LootableContainerBlockEntity.class.getDeclaredField("field_12037");
                lootTableSeedField = LootableContainerBlockEntity.class.getDeclaredField("field_12036");
            } catch (NoSuchFieldException e){
                throw new RuntimeException("找不到字段！", e);
            }
        }
        lootTableSeedField.setAccessible(true);
        lootTableIdField.setAccessible(true);
    }

    @Override
    public void onInitialize() {
        UseBlockCallback.EVENT.register((playerEntity, world, hand, blockHitResult) -> {
            if(!config.isEnable){return ActionResult.PASS;}
            if(world.isClient){return ActionResult.SUCCESS;}
            if(world.getBlockEntity(blockHitResult.getBlockPos()) instanceof LootableContainerBlockEntity entity){
                long seed;
                try {
                    if (lootTableIdField.get(entity) == null) {
                        return ActionResult.PASS;
                    }
                    seed = (long) lootTableSeedField.get(entity);
                } catch (IllegalAccessException e) {
                    return ActionResult.PASS;
                }
                if(ChineseChestFun.hasSeed(seed)){
                    return ActionResult.PASS;
                }
                var p = PacketByteBufs.create();
                p.writeBlockPos(blockHitResult.getBlockPos());
                p.writeLong(seed);
                ServerPlayNetworking.send((ServerPlayerEntity) playerEntity, ChineseChestNetworkID.OPEN_SCREEN, p);
                return ActionResult.FAIL;
            }
            return ActionResult.PASS;
        });
        ServerPlayNetworking.registerGlobalReceiver(ChineseChestNetworkID.SEND_ANSWER, (minecraftServer, serverPlayerEntity, serverPlayNetworkHandler, packetByteBuf, packetSender) -> {
            packetByteBuf.readBlockPos();
            var s = packetByteBuf.readLong();
            var m = packetByteBuf.readFloat();
            ChineseChestFun.addItemMultiple(s, m * config.baseMultiple);
            serverPlayerEntity.sendMessage(Text.translatable("gui.chinese_chest.message",
                    String.format("%.0f", m * 100)));
        });

        AutoConfig.register(ChineseChestConfig.class, GsonConfigSerializer::new);
        config = AutoConfig.getConfigHolder(ChineseChestConfig.class).getConfig();
        ChineseChestFun.initPoems(FabricLoader.getInstance().getConfigDir().resolve("ChineseChestFiles")
                .resolve(config.poemFile));
    }
}
